package me.leon.classical

import com.gitee.wsl.ext.string.letters
import com.gitee.wsl.security.encrypt.Encrypt
import com.gitee.wsl.security.encrypt.StringToStringEncrypt

/** @link https://zh.wikipedia.org/wiki/%E4%B8%80%E6%AC%A1%E6%80%A7%E5%AF%86%E7%A2%BC%E6%9C%AC */

class OneTimePadCipher(val key: String) : StringToStringEncrypt {
    override fun decrypt(src: String): String {
        val k2 = key.letters().uppercase()
        val d2 = src.letters().uppercase()
        val isSameSize = k2.length == d2.length
        if (!isSameSize) return src
        return d2.mapIndexed { index, c -> 'A' + (c.code - k2[index].code + 26) % 26 }.joinToString("")
    }

    override fun encrypt(src: String): String {
        val k2 = key.letters().uppercase()
        val d2 = src.letters().uppercase()
        val isSameSize = k2.length == d2.length
        if (!isSameSize) return src
        return d2.mapIndexed { index, c -> 'A' + (c.code + k2[index].code - 130) % 26 }.joinToString("")

    }

}

fun Encrypt.Companion.oneTimePadCipher( key: String) = OneTimePadCipher(key)